package lv.solcraft.replication.server.rest.restlets;

import lv.solcraft.replication.server.bdb.Database;
import lv.solcraft.replication.server.bdb.Database.OperSiteStore;
import lv.solcraft.replication.server.dao.OperSiteDataAccess;
import lv.solcraft.replication.server.dao.OperSiteDataAccessFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

public class ServerStatusResource extends Resource {

    private Database database;

    public void setDatabase(Database database) {
        this.database = database;
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public Representation getRepresentation(Variant variant) {
        JSONObject serverStatusJson = new JSONObject();
        long operCount = database.getOperDataAccess().countAll();
        serverStatusJson.put("operCount", operCount);
        OperSiteDataAccessFactory operSiteDataAccessFactory = database.getOperSiteDataAccessFactory();
        JSONArray operSitesJson = new JSONArray();
        for (OperSiteStore operSiteStore : database.getOperSiteStores()) {
            OperSiteDataAccess da = operSiteDataAccessFactory.getInstance(operSiteStore.getSiteId(), operSiteStore.getOperState());
            long operSiteCount = da.countAll();
            JSONObject operSiteJson = new JSONObject();
            operSiteJson.put("siteId", operSiteStore.getSiteId());
            operSiteJson.put("operState", operSiteStore.getOperState());
            operSiteJson.put("count", operSiteCount);
            operSitesJson.add(operSiteJson);
        }
        serverStatusJson.put("operSites", operSitesJson);
        return new StringRepresentation(serverStatusJson.toString(2));
    }

    @Override
    public boolean allowGet() {
        return true;
    }
}
